﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;

namespace Com.Maiyoule.GsmSms {
    class ComPort {

        private SerialPort sp = new SerialPort();


        /// <summary>
        /// 使用默认设置初始化端口
        /// </summary>
        public ComPort()
            : this(new Setting()) {



        }
        /// <summary>
        /// 使用自定义设置初始化端口
        /// </summary>
        /// <param name="setting"></param>
        public ComPort(Setting setting) {
            sp.BaudRate = setting.Rate;
            sp.DataBits = setting.Bits;
            sp.DtrEnable = setting.DtrEnabled;
            sp.PortName = setting.PortName;
            sp.ReadTimeout = setting.ReadTimeout;
            sp.RtsEnable = setting.RtsEnabled;
            sp.StopBits = setting.StopBits;
            sp.Parity = setting.Parity;
            sp.Handshake = setting.Handshake;
            sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
        }

        private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e) {
            OnDataReceived(e);
        }
        private virtual void OnDataReceived(EventArgs e) {
            if (DataReceived != null) {
                DataReceived(this, EventArgs.Empty);
            }
        }
        public event EventHandler DataReceived;


        /// <summary>
        /// 关闭串口
        /// </summary>
        /// <returns></returns>
        public bool Close() {
            try {
                sp.Close();
                return true;
            } catch {
                return false;
            }
        }
        /// <summary>
        /// 丢弃缓冲区数据
        /// </summary>
        /// <returns></returns>
        public bool DiscardInBuffer() {
            try {
                sp.DiscardInBuffer();
                return true;
            } catch {
                return false;
            }
        }
        /// <summary>
        /// 打开串口
        /// </summary>
        /// <returns></returns>
        public bool Open() {
            try {
                sp.Open();
                return true;
            } catch {
                return false;
            }
        }

        public int ReadByte() {

            return sp.ReadByte();
        }

        public int ReadChar() {
            return sp.ReadChar();
        }

        public string ReadExisting() {
            return sp.ReadExisting();
        }

        public string ReadLine() {
            return sp.ReadLine();
        }

        public string ReadTo(string value) {
            return sp.ReadTo(value);
        }

        public void Write(string text) {
            sp.Write(text);
        }

        public void WriteLine(string text) {
            sp.WriteLine(text);
        }
        public bool IsOpen() {
            return sp.IsOpen;
        }
    }
}
